using System;
using System.IO;
using System.Timers;


namespace monoServer
{
	// TODO Wenn Client und Server auf einer Maschine laufen, wird /var/log/bugserver/telegrams/* unübersichtlich weil beide Ihre
	// Eintragungen machen
	public class Logger
	{
		private Configuration c;
		private DateTime lastLog;
		
		public const int FILE = 1;
		public const int TERMINAL = 2;
		
		public Logger (Configuration c)
		{
			this.c = c;
			this.lastLog = DateTime.Now;
				
			//this.FILE = 1;
			//this.TERMINAL = 2;
		}
		
		public void writeInfo(int mode, string msg)
		{
			string line = DateTime.Now.ToString("HH:mm:ss:fff") + " - INFO - " + msg;
			this.write(mode, line);
		}
		
		public void writeWarning(int mode, string msg)
		{
			string line = DateTime.Now.ToString("HH:mm:ss:fff") + " - WARNING - " + msg;
			this.write(mode, line);
		}
		
		public void writeError(int mode, string msg)
		{
			string line = DateTime.Now.ToString("HH:mm:ss:fff") + " - ERROR - " + msg;
			this.write(mode, line);
		}
		
		public void writeError(int mode, Error e)
		{
			string line = DateTime.Now.ToString("HH:mm:ss:fff") + " - ERROR - " + e.toString();
			this.write(mode, line);
		}
		
		public void writeDebug(int mode, string msg)
		{
			if(bool.Parse((string)this.c.values["debug_mode"]))
			{
				string line = DateTime.Now.ToString("HH:mm:ss:fff") + " - DEBUG - " + msg;
				this.write(mode, line);
			}
		}
		
		private void write(int mode, string msg)
		{
			this.lastLog = DateTime.Now;
			switch (mode)
			{
			case Logger.FILE:
				this.writeToFile(msg);
				break;
			case Logger.TERMINAL:
				this.writeToTerminal(msg);
				break;
			case Logger.FILE + Logger.TERMINAL:
				this.writeToFile(msg);
				this.writeToTerminal(msg);
				break;
			}
		}
		
		private void writeToTerminal(string msg)
		{
			Console.WriteLine(msg);
		}
		
		private void writeToFile(string msg)
		{
			StreamWriter sw = File.AppendText((string)this.c.values["logdir"] + DateTime.Now.ToString("yyyy.MM.dd"));
			sw.WriteLine(msg);
			sw.Flush();
			sw.Close();
		}
		
		public void writeTelegramToFile(string msg, bool r_or_s)
		{
			// TODO Client-Informationwn (IP, Session u.s.w. müssen dazu)
			StreamWriter sw = File.AppendText((string)this.c.values["logdirt"] + DateTime.Now.ToString("yyyy.MM.dd"));
			string arrow = null;
			if(r_or_s)
				arrow = "<-- ";
			else
				arrow = "--> ";
			sw.WriteLine(arrow + msg);
			sw.Flush();
			sw.Close();
		}
		
		public void writeServerAliveToLog(object sender, ElapsedEventArgs e)
		{
			if((this.lastLog.AddMinutes(int.Parse((string)this.c.values["alive_keep_out_time"]))).CompareTo(DateTime.Now) <= 0)
			{
				this.writeInfo(Logger.FILE+Logger.TERMINAL,"Server Alive!");
			}
		}
		
		/*
		private void log(int mode, string level, string msg)
		{
			
		}
		*/
		
	}
}

